package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.DepartmentManagement.DepartmentMapper;
import aiku.numericalcontroloa.Mapper.DepartmentManagement.EmployeeDepartmentMapper;
import aiku.numericalcontroloa.Mapper.UserMapper;
import aiku.numericalcontroloa.Model.Dto.EmployeeAttendance.AttendanceDto;
import aiku.numericalcontroloa.Model.Dto.ExportExcel.AttendanceExcelDto;
import aiku.numericalcontroloa.Model.Dto.OrderManagement.OrderDto;
import aiku.numericalcontroloa.Model.Entity.DepartmentManagement.Department;
import aiku.numericalcontroloa.Model.Entity.DepartmentManagement.EmployeeDepartmentWithUser;
import aiku.numericalcontroloa.Model.Entity.User;
import aiku.numericalcontroloa.Model.Vo.EmployeeAttendance.AttendanceVo;
import aiku.numericalcontroloa.Service.DepartmentManagement.EmployeeDepartmentService;
import aiku.numericalcontroloa.Service.EmployeeAttendance.AttendanceService;
import aiku.numericalcontroloa.Service.EmployeeAttendance.Impl.AttendanceServiceImpl;
import aiku.numericalcontroloa.Service.ExportExcelService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author 黄广庭
 * @Date 2024/3/13 11:14
 */
@Service
public class ExportExcelServiceImpl implements ExportExcelService {
    // 导出Excel后下载映射的路径
    @Value("${numericalControlOa.excelPath}")
    private String excelPath;
    // 导出Word后下载映射的路径
    @Value("${numericalControlOa.wordPath}")
    private String wordPath;

    private final UserMapper userMapper;
    private final AttendanceService attendanceService;
    private final EmployeeDepartmentService employeeDepartmentService;
    private final EmployeeDepartmentMapper employeeDepartmentMapper;
    private final DepartmentMapper departmentMapper;

    public ExportExcelServiceImpl(UserMapper userMapper, AttendanceService attendanceService, EmployeeDepartmentService employeeDepartmentService, EmployeeDepartmentMapper employeeDepartmentMapper, DepartmentMapper departmentMapper) {
        this.userMapper = userMapper;
        this.attendanceService = attendanceService;
        this.employeeDepartmentService = employeeDepartmentService;
        this.employeeDepartmentMapper = employeeDepartmentMapper;
        this.departmentMapper = departmentMapper;
    }

    @Override
    public Result attendanceStatistics(AttendanceExcelDto attendanceExcelDto) {
//        if (attendanceExcelDto == null){
//            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
//        }
//
//        // 文件名
//        String fileName;
//        String date;
//
//        // 查找数据
//        AttendanceDto attendanceDto = new AttendanceDto();
//        if (attendanceExcelDto.getYear() != null){
//            attendanceDto.setYear(attendanceExcelDto.getYear());
//            date = attendanceExcelDto.getYear().toString();
//        }else if(attendanceExcelDto.getYearMonth() != null){
//            attendanceDto.setYearMonth(attendanceExcelDto.getYearMonth());
//            date = attendanceExcelDto.getYearMonth().toString();
//        }else if(attendanceExcelDto.getYearMonthDay() != null){
//            attendanceDto.setYearMonthDay(attendanceExcelDto.getYearMonthDay());
//            date = attendanceExcelDto.getYearMonthDay().toString();
//        }else {
//            attendanceDto.setYearMonth(YearMonth.now());
//            date = YearMonth.now().toString();
//        }
//
//        List<User> userList = new ArrayList<>();
//
//        if (attendanceExcelDto.getDepartmentId() != null){
//            // 按部门查用户
//            Department department = departmentMapper.selectById(attendanceExcelDto.getDepartmentId());
//            fileName = department.getName()+"出勤表";
//
//            // 先查询该部门所有下级部门
//            List<String> departmentIdList = new ArrayList<>();
//            departmentIdList.add(attendanceExcelDto.getDepartmentId());
//            employeeDepartmentService.getDepartmentIdList(departmentIdList,departmentIdList);
//            // 去重
//            Set<String> departmentIds = new HashSet<>(departmentIdList);
//            QueryWrapper<EmployeeDepartmentWithUser> employeeDepartmentLQW = new QueryWrapper<>();
//            employeeDepartmentLQW.lambda().in(EmployeeDepartmentWithUser::getDepartmentId,departmentIds);
//            Set<String> userIdList = employeeDepartmentMapper.selectListWithUser(null, employeeDepartmentLQW.lambda())
//                    .stream().map(EmployeeDepartmentWithUser::getEmployeeId).collect(Collectors.toSet());
//            userList.addAll(userMapper.selectBatchIds(userIdList));
//        }else {
//            // 查询所有用户
//            userList.addAll(userMapper.selectList(null));
//            fileName = "员工出勤表";
//        }
//        AttendanceServiceImpl attendanceService1 = (AttendanceServiceImpl)attendanceService;
//
//        // 导出数据
//        // 统计工作表
//        HSSFWorkbook workbook = new HSSFWorkbook();
//        List<AttendanceVo> attendanceList = attendanceService1.getAttendanceVoList(userList,attendanceDto);
//        HSSFSheet sheet = workbook.createSheet("统计");
//        // 添加表头信息
//        String[] columns = {"序号","姓名","正常打卡","迟到","早退","旷工","请假","外勤","出差","出勤天数"};
//        HSSFRow headerRow = sheet.createRow(0); // 表头行
//        for (int i = 0; i < columns.length; i++) {
//            headerRow.createCell(i).setCellValue(columns[i]);
//        }
//
//        for (int rowIndex = 0; rowIndex < attendanceList.size(); rowIndex++) {
//            HSSFRow row = sheet.createRow(rowIndex + 1); // 从第二行开始插入数据
//            AttendanceVo attendance = attendanceList.get(rowIndex);
//            row.createCell(0).setCellValue(rowIndex+1); // 工号
//            row.createCell(1).setCellValue(attendance.getNickName()); // 姓名
//            row.createCell(2).setCellValue(attendance.getNormalTotal()); // 正常打卡
//            row.createCell(3).setCellValue(attendance.getLateTotal()); // 迟到
//            row.createCell(4).setCellValue(attendance.getTardyTotal()); // 早退
//            row.createCell(5).setCellValue(attendance.getAbsenteeismTotal()); // 旷工
//            row.createCell(6).setCellValue(attendance.getLeaveTotal()); // 请假
//            row.createCell(7).setCellValue(attendance.getWorkOutsideTotal()); // 外勤
//            row.createCell(8).setCellValue(attendance.getBusinessTripTotal()); // 出差
//            row.createCell(9).setCellValue(attendance.getAttendanceDays()); // 出勤天数
//        }
//
//
//        List<List<AttendanceVo>> data = new ArrayList<>();
//        for (int sheetIndex = 1; sheetIndex < data.size(); sheetIndex++) {
//
//        }
//        // 保存文件
//        fileName = fileName+date+".xlsx";
//        String filePath = excelPath + fileName;
//        File file = new File(excelPath);
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//        try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
//            workbook.write(fileOut);
//            workbook.close();
//            return Result.success("导出成功",fileName);
//        } catch (IOException e) {
//            e.printStackTrace();
//            return Result.error("导出失败");
//        }
        if (attendanceExcelDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }

// 文件名
        String fileName;
        String date;

// 查找数据
        AttendanceDto attendanceDto = new AttendanceDto();
        if (attendanceExcelDto.getYear() != null) {
            attendanceDto.setYear(attendanceExcelDto.getYear());
            date = attendanceExcelDto.getYear().toString();
        } else if (attendanceExcelDto.getYearMonth() != null) {
            attendanceDto.setYearMonth(attendanceExcelDto.getYearMonth());
            date = attendanceExcelDto.getYearMonth().toString();
        } else if (attendanceExcelDto.getYearMonthDay() != null) {
            attendanceDto.setYearMonthDay(attendanceExcelDto.getYearMonthDay());
            date = attendanceExcelDto.getYearMonthDay().toString();
        } else {
            attendanceDto.setYearMonth(YearMonth.now());
            date = YearMonth.now().toString();
        }

        List<User> userList = new ArrayList<>();

        if (attendanceExcelDto.getDepartmentId() != null) {
            // 按部门查用户
            Department department = departmentMapper.selectById(attendanceExcelDto.getDepartmentId());
            fileName = department.getName() + "出勤表";

            // 先查询该部门所有下级部门
            List<String> departmentIdList = new ArrayList<>();
            departmentIdList.add(attendanceExcelDto.getDepartmentId());
            employeeDepartmentService.getDepartmentIdList(departmentIdList, departmentIdList);
            // 去重
            Set<String> departmentIds = new HashSet<>(departmentIdList);
            QueryWrapper<EmployeeDepartmentWithUser> employeeDepartmentLQW = new QueryWrapper<>();
            employeeDepartmentLQW.lambda().in(EmployeeDepartmentWithUser::getDepartmentId, departmentIds);
            Set<String> userIdList = employeeDepartmentMapper.selectListWithUser(null, employeeDepartmentLQW.lambda())
                    .stream().map(EmployeeDepartmentWithUser::getEmployeeId).collect(Collectors.toSet());
            userList.addAll(userMapper.selectBatchIds(userIdList));
        } else {
            // 查询所有用户
            userList.addAll(userMapper.selectList(null));
            fileName = "员工出勤表";
        }

        AttendanceServiceImpl attendanceService1 = (AttendanceServiceImpl) attendanceService;

// 导出数据
// 统计工作表
        XSSFWorkbook workbook = new XSSFWorkbook();
        List<AttendanceVo> attendanceList = attendanceService1.getAttendanceVoList(userList, attendanceDto);
        XSSFSheet sheet = workbook.createSheet("统计");

// 添加表头信息
        String[] columns = {"序号", "姓名", "正常打卡", "迟到", "早退", "旷工", "请假", "外勤", "出差", "出勤天数"};
        XSSFRow headerRow = sheet.createRow(0); // 表头行
        for (int i = 0; i < columns.length; i++) {
            headerRow.createCell(i).setCellValue(columns[i]);
        }

// 填充数据
        for (int rowIndex = 0; rowIndex < attendanceList.size(); rowIndex++) {
            XSSFRow row = sheet.createRow(rowIndex + 1); // 从第二行开始插入数据
            AttendanceVo attendance = attendanceList.get(rowIndex);
            row.createCell(0).setCellValue(rowIndex + 1); // 序号
            row.createCell(1).setCellValue(attendance.getNickName()); // 姓名
            row.createCell(2).setCellValue(attendance.getNormalTotal()); // 正常打卡
            row.createCell(3).setCellValue(attendance.getLateTotal()); // 迟到
            row.createCell(4).setCellValue(attendance.getTardyTotal()); // 早退
            row.createCell(5).setCellValue(attendance.getAbsenteeismTotal()); // 旷工
            row.createCell(6).setCellValue(attendance.getLeaveTotal()); // 请假
            row.createCell(7).setCellValue(attendance.getWorkOutsideTotal()); // 外勤
            row.createCell(8).setCellValue(attendance.getBusinessTripTotal()); // 出差
            row.createCell(9).setCellValue(attendance.getAttendanceDays()); // 出勤天数
        }

// 保存文件
        fileName = fileName + date + ".xls"; // 注意文件扩展名为.xls
        String filePath = excelPath + fileName;
        File file = new File(excelPath);
        if (!file.exists()) {
            file.mkdirs();
        }

        try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("导出失败");
        } finally {
            // 确保工作簿在结束时关闭
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return Result.success("导出成功", fileName);
    }

    @Override
    public Result generateContract(OrderDto orderDto) {
        return null;
    }
}
